package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.PageHelperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void update(Region region) {

        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {


        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {

        //查询封装类
        Query query = new Query();

        //分页数据 , currentPage , pageSite
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");

        Page<Region> page = PageHelperUtil.query(template, pageable, Region.class, query, qo);
        //list Pageable total 封装三个数据,返回给页面
        return page;
    }

    @Override
    public void saveOrUpdate(Region region) {

        //update
        //mongodb - repository 的更新操作时全量更新
        //为什么此处操作没有出现参数丢失问题
        //region 编辑时页面修改数据个数刚好跟表中列个数一致
        //即全量修改
        if (StringUtils.hasLength(region.getId())){

            this.update(region);
        }else {
            this.save(region);
        }
    }

    @Override
    public void changeHotValue(int hot, String id) {

        Query query = new Query();

        //部分字段更新   db.集合名.updateMany({_id:id},{$set:{ishot:hot}})
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot",hot );
        template.updateMulti(query, update, Region.class);

    }

    @Override
    public List<Region> findByIshot() {

        List<Region> list = repository.findByIshotOrderBySequence(Region.STATE_HOT);
        return list;
    }


}
